package com.nf28.removies;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.nf28.removies.api.Movie;
import com.nf28.removies.api.RequestResult;
import com.nf28.removies.coverflow.CoverFlowItem;
import com.nf28.removies.coverflow.CoverFlowView;
import com.nf28.removies.keys.KeysIntent;
import com.nf28.removies.viewtimeline.TimeLineView;

import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import android.text.Editable;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Gravity;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("NewApi")
public class MainActivity extends Activity implements TextWatcher,CoverFlowView.Listener {



	AutoCompleteTextView input = null;


	CoverFlowView mCoverflowBoxOffice;
	CoverFlowView mCoverflowResults = null;

	List<Movie> listFilmsBoxOffice;
	List<Movie> listFilmsResult; 
	// liste qui va contenir les films obtenus apres la recherche
	//Cette liste va etre utilisee pour passer a la vue Film

	Button goToMesFilms;

	Button clickOnly = null; 
	Button left = null; 
	Button right = null; 
	RequestResult resultObject = null;
	RequestResult resultObject2 = null;
	Movie movie = null;
	int currentMovie = 0;


	AutoCompleteTextView myAutoComplete;
	List<String> MoviesPredictive = new ArrayList<String>();


	/******************** Ajout pour cover flow **********************/

	private static final String TAG = "CoverFlowActivity";
	private static int NUMBER_FILM_BOXOFFICE = 10;
	private static int NUMBER_FILM_RESULTS = 0;
	private Bitmap[] mReflectedBitmaps;
	private boolean mCoverflowCleared = false;

	public static final int NUMBER_OF_IMAGES = 30;
	private static final int IO_BUFFER_SIZE = 4 * 1024;

	public class DownloadImagesTask extends AsyncTask<String, Void, Bitmap> {

		public int index;
		public Bitmap b;
		CoverFlowView coverFlowView;

		DownloadImagesTask(int i, CoverFlowView mCoverflow){
			index = i;
			this.coverFlowView = mCoverflow;
		}


		@Override
		protected Bitmap doInBackground(String... urls) {
			b = download_Image(urls[0]);
			return null;
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			//mCoverflowBoxOffice.setBitmapForIndex(b, index);
			coverFlowView.setBitmapForIndex(b, index);
		}


		private Bitmap download_Image(String url) {
			//---------------------------------------------------
			Bitmap bm = null;
			try {
				URL aURL = new URL(url);
				URLConnection conn = aURL.openConnection();
				conn.connect();
				InputStream is = conn.getInputStream();
				BufferedInputStream bis = new BufferedInputStream(is);
				bm = BitmapFactory.decodeStream(bis);
				bis.close();
				is.close();
			} catch (IOException e) {
				Log.e("Hub","Error getting the image from server : " + e.getMessage().toString());
			} 
			return bm;
			//---------------------------------------------------
		}
	}
	

	private boolean isNetworkAvailable() {
		ConnectivityManager connectivityManager 
		= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
		return activeNetworkInfo != null && activeNetworkInfo.isConnected();
	}


	/******************************************************************/

	//------------------------------------------------------
	//	 @Override
	//	 public void onSaveInstanceState(Bundle savedInstanceState) {
	//	   // Save UI state changes to the savedInstanceState.
	//	   // This bundle will be passed to onCreate if the process is
	//	   // killed and restarted.
	//		 savedInstanceState.putAll(savedInstanceState);
	//		 /*
	//	  savedInstanceState.putBoolean("MyBoolean", true);
	//	  savedInstanceState.putDouble("myDouble", 1.9);
	//	  savedInstanceState.putInt("MyInt", 1);
	//	  savedInstanceState.putString("MyString", "Welcome back to Android");
	//	  // etc.
	//	   * 
	//	   * */
	//	   
	//	  super.onSaveInstanceState(savedInstanceState);
	//	  }

	

	@SuppressLint("NewApi")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);



		

		setContentView(R.layout.activity_main);   

		if(isNetworkAvailable()){

			input = (AutoCompleteTextView)findViewById(R.id.editText1); 
			input.addTextChangedListener(this);
			input.setOnItemClickListener(new OnItemClickListener(){
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {  
					Log.i("click","afficher la vue du film");


					RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
					params. topMargin= 230;
					mCoverflowBoxOffice.setLayoutParams(params);
					mCoverflowBoxOffice.setScaleX(1f);
					mCoverflowBoxOffice.setScaleY(1f);

					try {
						resultObject2 = Request.searchMovie(input.getText().toString());
					} catch (IOException e) {
						e.printStackTrace();
					}
					if(resultObject2 != null  && resultObject2.getTotal_results()>0){

						if(resultObject2.getTotal_results()>0){
							NUMBER_FILM_RESULTS =  resultObject2.getResults().length;

							int nbFilmsAvecAfficheAccessibles = 0;
							for(int k = 0; k<NUMBER_FILM_RESULTS; k++){
								String res = resultObject2.getResults()[k].getPoster_path();
								if (res!=null)
									nbFilmsAvecAfficheAccessibles++;
							}

							if (nbFilmsAvecAfficheAccessibles >0){
								
								for (int i = 0;  i < nbFilmsAvecAfficheAccessibles; i++) {
									try {
										mCoverflowResults.setBitmapForIndex(BitmapFactory.decodeStream(getAssets().open("images/default_cover.png")), i);
									} catch (IOException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
								}

								listFilmsResult = new ArrayList();
								mCoverflowResults.setNumberOfImages(nbFilmsAvecAfficheAccessibles);
								mCoverflowResults.setSelectedCover(0); 
								int ind=0;
								for(int k = 0; k<NUMBER_FILM_RESULTS; k++){

									String res = resultObject2.getResults()[k].getPoster_path();
									if (res!=null){
										new DownloadImagesTask(ind++,mCoverflowResults).execute(Request.path_to_url(res,"w92"));
										listFilmsResult.add(resultObject2.getResults()[k]);
									}
								}
								NUMBER_FILM_RESULTS = nbFilmsAvecAfficheAccessibles;
								
							}
						}
					}

				} 

			});

			input.addTextChangedListener(new TextWatcher() {
				public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

				public void onTextChanged(CharSequence s, int start, int before, int count) {  
					//predictive search 3 by 3 characters, if before equal 1 you are erasing 
		 	        if(before == 0)
		 	        {
					
						//predictive search 3 by 3 characters
						if(s.toString().length() != 0 && s.toString().length() % 3 == 0){
							try {
								resultObject = Request.searchMovie(s.toString());
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							if(resultObject != null){
								for(int i =0;i<resultObject.getResults().length;i++){
									movie = resultObject.getResults()[i];
									//Log.i("title ",movie.getOriginal_title());
									//Log.i("title avec ", String.valueOf(movie.getOriginal_title().toLowerCase(Locale.US).indexOf(s.toString().toLowerCase(Locale.US))));
									if(movie.getOriginal_title() != null && movie.getOriginal_title().toLowerCase(Locale.US).indexOf(s.toString().toLowerCase(Locale.US))>-1){
										Log.i("un titre", movie.getOriginal_title());
										MoviesPredictive.add(movie.getOriginal_title());
									}
								}
								input.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_dropdown_item_1line, MoviesPredictive));
								
							}
						}    
		 	        }
				}

				@Override
				public void afterTextChanged(Editable arg0) {
					// TODO Auto-generated method stub

				}
			});


			clickOnly = (Button)findViewById(R.id.validButton);
			clickOnly.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					currentMovie = 0;


					RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
					params. topMargin= 230;
					mCoverflowBoxOffice.setLayoutParams(params);
					mCoverflowBoxOffice.setScaleX(1f);
					mCoverflowBoxOffice.setScaleY(1f);

					
					
					
					
					

					try {
						resultObject2 = Request.searchMovie(input.getText().toString());
						if(resultObject2 != null  && resultObject2.getTotal_results()>0){
							//movie = resultObject.getResults()[currentMovie];
							//String imageUrl = null;

							//------------------                                            
							//NUMBER_FILM_RESULTS =  resultObject2.getTotal_results();
							NUMBER_FILM_RESULTS =  resultObject2.getResults().length;


							int nbFilmsAvecAfficheAccessibles = 0;
							for(int k = 0; k<NUMBER_FILM_RESULTS; k++){

								String res = resultObject2.getResults()[k].getPoster_path();
								if (res!=null)
									nbFilmsAvecAfficheAccessibles++;
							}

							if (nbFilmsAvecAfficheAccessibles >0){
								
								for (int i = 0;  i < nbFilmsAvecAfficheAccessibles; i++) {
									try {
										mCoverflowResults.setBitmapForIndex(BitmapFactory.decodeStream(getAssets().open("images/default_cover.png")), i);
									} catch (IOException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
								}
								

								listFilmsResult = new ArrayList<Movie>();

								mCoverflowResults.setNumberOfImages(nbFilmsAvecAfficheAccessibles);
								mCoverflowResults.setSelectedCover(0); 
								int ind=0;
								for(int k = 0; k<NUMBER_FILM_RESULTS; k++){
									String res = resultObject2.getResults()[k].getPoster_path();
									if (res!=null){
										new DownloadImagesTask(ind++,mCoverflowResults).execute(Request.path_to_url(res,"w92"));
										listFilmsResult.add(resultObject2.getResults()[k]);
									}

								}
								NUMBER_FILM_RESULTS = nbFilmsAvecAfficheAccessibles;
								

				
							}

							//------------------------------------------
							//if(movie.getOriginal_title() != null)
							//result.setText(movie.getOriginal_title());                
						}
						else{
						}
					} catch (UnsupportedEncodingException e1) {
						e1.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}


				}
			});     



			// ***************************************************************** Find the coverflowBoxOffice
			mCoverflowBoxOffice = (CoverFlowView) findViewById(R.id.coverflowBoxOffice);

			//mCoverflowBoxOffice.set

			// Listen to the coverflow
			mCoverflowBoxOffice.setListener(this);
			// Fill in images
			for (int i = 0;  i < 10; i++) {
				try {
					mCoverflowBoxOffice.setBitmapForIndex(BitmapFactory.decodeStream(getAssets().open("images/default_cover.png")), i);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}


			mCoverflowBoxOffice.setNumberOfImages(NUMBER_FILM_BOXOFFICE);
			// Cache the reflected bitmaps
			mReflectedBitmaps = mCoverflowBoxOffice.getReflectedBitmaps();
			//result = (TextView)findViewById(R.id.textView1);

			RequestResult resultObject = null;
			try {
				resultObject = Request.searchBoxOffice();
			} catch (IOException e) {
				e.printStackTrace();
			}
			Bitmap[] bitmaps = new Bitmap[NUMBER_FILM_BOXOFFICE];
			String urlimg = null;

			if(resultObject.getResults().length>=NUMBER_FILM_BOXOFFICE){
				listFilmsBoxOffice = new ArrayList<Movie>();
				int ind=0;
				for(int i = 0; i<NUMBER_FILM_BOXOFFICE; i++){

					String imageStr = resultObject.getResults()[i].getPoster_path();
					if (imageStr != null){
						new DownloadImagesTask(ind++,mCoverflowBoxOffice).execute(Request.path_to_url(imageStr,"w92"));
						listFilmsBoxOffice.add(resultObject.getResults()[i]);
					}

				}
			}

			
			Log.i("mCoverflowResults vaut null","-----------------------------------------");
			
			mCoverflowResults = (CoverFlowView) findViewById(R.id.coverflowResults);
			mCoverflowResults.setListener(this);
			mCoverflowResults.getReflectedBitmaps();
			


				mCoverflowBoxOffice.setScaleX(1.5f);
				mCoverflowBoxOffice.setScaleY(1.5f);

		}
		else{
			Log.i("no network","popin");
			Toast msg = Toast.makeText(MainActivity.this, "you need an internet connection to acces movies search feature", Toast.LENGTH_LONG);
			msg.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
			msg.show();
		}

		goToMesFilms = (Button)findViewById(R.id.goToMesFilms);
		goToMesFilms.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) { 
				Intent intent = new Intent(MainActivity.this, TimeLineView.class);
				
				if(mCoverflowResults == null){
					
					Log.i("dans goToMesFilms mCoverflowResults vaut null","-----------------------------------------");
				}
				else
					Log.i("dans goToMesFilms mCoverflowResults non null","-----------------------------------------");
				
				startActivity(intent);
			}
		});

			

	}



	@Override
	public void afterTextChanged(Editable arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
			int arg3) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
		// TODO Auto-generated method stub

	}

	public void onSelectionChanged(CoverFlowView coverFlow, int index) {
		Log.d(TAG, String.format("Selection did change: %d", index));
	}

	public void onSelectionChanging(CoverFlowView coverFlow, int index) {
		Log.d(TAG, String.format("Selection is changing: %d", index));
	}

	public void onSelectionClicked(CoverFlowView coverFlow, int index) { // FIX ME : ici, vue de Sofien
		Movie movieSelected = null ;
		Log.d(TAG, String.format("Selection clicked: %d", index));
		int idMovieSelected = 0;
		if (coverFlow == mCoverflowResults){
			Log.i("mCoverflowResults , index : ",""+index);
			movieSelected = listFilmsResult.get(index);
			Log.i("film choisi :", movieSelected.getOriginal_title());
		}
		else if (coverFlow == mCoverflowBoxOffice){
			Log.i("mCoverflowBoxOffice , index : ",""+index);
			movieSelected = listFilmsBoxOffice.get(index);
			Log.i("film choisi :", movieSelected.getOriginal_title());
		}


		idMovieSelected = movieSelected.getId();

		Log.i("le film choisi a l'id ", String.valueOf(idMovieSelected));

		Intent intent = new Intent(MainActivity.this, AddFilm.class);
		intent.putExtra(KeysIntent.EXTRA_ID, String.valueOf(idMovieSelected));

		startActivity(intent);


	}

}